/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.starmeep.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.jcraft.jsch.JSchException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.starmeep.classes.StarCluster;
import org.starmeep.classes.StarJob;
import org.starmeep.classes.StarMeep;
import org.starmeep.client.GWTService;
import org.starmeep.config.*;
import sun.security.provider.ConfigSpiFile;
/**
 *
 * @author CARLOS
 */
public class GWTServiceImpl extends RemoteServiceServlet implements GWTService {
    public Boolean finalizaConfiguration(Map dataForm) {
        ConfigStarCluster config=new ConfigStarCluster();
        System.out.print("entrada finaliza configuration rpc");
        try
        {
            HttpSession sesion=this.getThreadLocalRequest().getSession();
            String directoryConfiguration=ConfigStarCluster.pathConfigurationStarCluster;
            File directorio = new File(directoryConfiguration);
            FileWriter fw = new FileWriter(directorio);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter salida = new PrintWriter(bw);

            Cluster starmeep=new Cluster("starmeep", Cluster.pathKeyLocation+dataForm.get("keyLocation"), dataForm.get("keyName").toString(), dataForm.get("cbSizeTotal").toString(), "sgeadmin", dataForm.get("cbShell").toString(),"ami-22d63e4b", "c1.medium", "ami-22d63e4b", "c1.medium", dataForm.get("cbZone").toString());
            ArrayList<Cluster> listCluster=new ArrayList<Cluster>();
            listCluster.add(starmeep);
            if(!dataForm.get("ebsVolumeId").equals(""))
            {
                EBSVolume volume= new EBSVolume("data",dataForm.get("ebsVolumeId").toString(),dataForm.get("ebsDevice").toString(),dataForm.get("ebsPartition").toString(),dataForm.get("ebsMountPath").toString());
                ArrayList<EBSVolume> listVolumen=new ArrayList<EBSVolume>();
                listVolumen.add(volume);
                config.setVolumenes(listVolumen);
            }
            System.out.print("mitad finaliza configuration rpc");
            config.setAccount(dataForm.get("accountNumber").toString());
            config.setAwsKey(dataForm.get("awsKey").toString());
            config.setSecretKey(dataForm.get("secretAws").toString());
            config.setClusteres(listCluster);
            sesion.setAttribute("configCurrent",config);
            writeFileConfiguration(config,salida);
        }catch(Exception e)
        {
            Logger.getLogger(GWTServiceImpl.class.getName()).log(Level.SEVERE, null, e);
            return false;
        }
        System.out.print("Salida finaliza configuration rpc");
        return true;
    }
    /*
     * 1 -> running
     * 0 -> config exists, but cluster is not running
     * -1 -> config doesn't exist, either running
     */
    public Map isClusterRunning(){
        HttpSession session=this.getThreadLocalRequest().getSession();
        StarCluster starcluster=(StarCluster) session.getAttribute("starcluster");
        HashMap configuration=null;
          
        if(starcluster==null)
        {
            ConfigStarCluster conf=ConfigStarCluster.readConfigFromFile(ConfigStarCluster.pathConfigurationStarCluster);
            if(conf==null)
                return null;
            session.setAttribute("configCurrent", conf);
            System.out.println("Existe la configuracion");
            configuration=conf.toHashMap();
            if(StarCluster.isRunningAlready())
            {
                System.out.println("Cluster is Running Already");
                starcluster=new StarCluster(true, conf.getClusteres().get(0).getClusterKeyLocation());
                session.setAttribute("starcluster", starcluster);
                configuration.put("isClusterRun","1");
                return configuration;
            }
            configuration.put("isClusterRun","0");
            return configuration;
        }
        else
        {
            ConfigStarCluster conf=(ConfigStarCluster)session.getAttribute("configCurrent");
            configuration=conf.toHashMap();
            configuration.put("isClusterRun","1");
            return configuration;
        }
    }
    private void writeFileConfiguration(ConfigStarCluster config,PrintWriter salida)
    {
            salida.println("[aws info]");
            salida.println("AWS_ACCESS_KEY_ID ="+config.getAwsKey());
            salida.println("AWS_SECRET_ACCESS_KEY ="+config.getSecretKey());
            salida.println("AWS_USER_ID="+config.getAccount());
            salida.println("[key "+config.getClusteres().get(0).getClusterKeyName()+"]");
            salida.println("KEY_LOCATION="+config.getClusteres().get(0).getClusterKeyLocation());
            if(config.getVolumenes()!=null)
            {
                salida.println("[volume "+config.getVolumenes().get(0).getVolumeName()+"]");
                salida.println("VOLUME_ID ="+config.getVolumenes().get(0).getVolumeID());
                salida.println("DEVICE ="+config.getVolumenes().get(0).getVolumeDevice());
                salida.println("PARTITION ="+config.getVolumenes().get(0).getVolumePartition());
                salida.println("MOUNT_PATH ="+config.getVolumenes().get(0).getVolumePathMount());
            }
            salida.println("[cluster starmeep]");
            salida.println("KEYNAME = "+config.getClusteres().get(0).getClusterKeyName());
            salida.println("CLUSTER_SIZE = "+config.getClusteres().get(0).getClusterSize());
            salida.println("CLUSTER_SHELL = "+config.getClusteres().get(0).getClusterShell());
            salida.println("MASTER_IMAGE_ID = "+config.getClusteres().get(0).getClusterMasterImage());
            salida.println("MASTER_INSTANCE_TYPE = "+config.getClusteres().get(0).getClusterMasterType());
            salida.println("NODE_IMAGE_ID = "+config.getClusteres().get(0).getClusterNodeImage());
            salida.println("NODE_INSTANCE_TYPE = "+config.getClusteres().get(0).getClusterNodeType());
            salida.println("AVAILABILITY_ZONE ="+config.getClusteres().get(0).getClusterZone());
            if(config.getVolumenes()!=null)
            {
                salida.println("# (OPTIONAL)");
                salida.println("VOLUMES = "+config.getVolumenes().get(0).getVolumeName());
            }
            salida.close();
    }
    public String launchCluster(Map dataForm){
        String response="";
        System.out.println("Si ingresa");
        HttpSession session=this.getThreadLocalRequest().getSession();

        System.out.println("Si ingresa");
        StarCluster starcluster=(StarCluster) session.getAttribute("starcluster");
        System.out.println("Si ingresa");
        if(starcluster==null){
            ConfigStarCluster conf=(ConfigStarCluster) session.getAttribute("configCurrent");
            if(conf==null){
                response = "Error: Set first a Configuration";
                return response;
            }
            System.out.println("Si ingresa");
            System.out.println(conf.getClusteres().get(0).getClusterKeyLocation());
            starcluster=new StarCluster(false, conf.getClusteres().get(0).getClusterKeyLocation());
            session.setAttribute("starcluster", starcluster);
        }
        System.out.println("cluster is running:"+starcluster.isRunning());
        if(starcluster.isRunning())
        {
            response=starcluster.stop();
            starcluster.setRunning(false);
            session.setAttribute("Jobs", null);
            session.setAttribute("starcluster", null);
            session.removeAttribute("starcluster");
            response+=" stopping";
            System.out.println("Llego a terminar de stopear");

        }
        else{
            starcluster.givePermissionKey();
            response=starcluster.start();
            starcluster.setRunning(true);
            response+=" starting";
        }
        System.out.println("Respuesta:"+response);
        return response;
    }
    public String viewJobs(Map dataForm){

        return"viewJobs";
    }
    public String viewHostStatus(Map dataForm){

        return "viewHostStatus";
    }
    public ArrayList<Map> showFiles(String jobName){
        ArrayList files=new ArrayList<Map>();
        
        HttpSession session=this.getThreadLocalRequest().getSession();
        Map jobs=(Map)session.getAttribute("Jobs");
        StarJob jobCurrent=(StarJob)jobs.get(jobName);

        files=jobCurrent.getMeep().getFilenamesSize();

        return files;
    }
    public String enterCommand(String nameJob,String command){

        HttpSession session=this.getThreadLocalRequest().getSession();
        Map jobs=(Map)session.getAttribute("Jobs");
        StarJob jobCurrent=(StarJob)jobs.get(nameJob);

        String res=jobCurrent.getMeep().customCommand(command);

        return res;
    }
    public String downloadFile(Map dataForm){
        return "downloadFile";
    }

    public String RunJob(String job)
    {
        String idJob="1";
        HttpSession session=this.getThreadLocalRequest().getSession();
        Map jobs=(Map)session.getAttribute("Jobs");
        StarJob jobCurrent=(StarJob)jobs.get(job);
        if(jobCurrent.getIsRunning())
        {
            jobCurrent.getMeep().stopCTL(jobCurrent.getId());
            jobCurrent.setIsRunning(false);
            jobCurrent.setId("-1");
            jobs.put(job, jobCurrent);
            return "-1";
        }
        else
        {
            idJob=jobCurrent.getMeep().runCTL(jobCurrent.getParameters());
            jobCurrent.setId(idJob);
            jobCurrent.setIsRunning(true);
            jobs.put(job, jobCurrent);
            session.setAttribute("Jobs", jobs);
            return idJob;
        }
    }
    public String deleteJob(String jobName)
    {
        System.out.println("Borrar el job"+jobName);
        HttpSession session=this.getThreadLocalRequest().getSession();
        Map jobs=(Map)session.getAttribute("Jobs");
        StarJob jobCurrent=(StarJob)jobs.remove(jobName);
        if(jobCurrent==null)
            System.out.println("El job era nullo no lo encontro");
        else
            jobCurrent.getMeep().deleteMeepMasterDir();
        return jobName;
    }
    public String checkJob(String jobName)
    {
        HttpSession session=this.getThreadLocalRequest().getSession();
        Map jobs=(Map)session.getAttribute("Jobs");
        StarJob jobCurrent=(StarJob)jobs.remove(jobName);
        String result="";

        result=jobCurrent.getMeep().qstat(jobCurrent.getId());
   
        return result;
    }
    public Map loadConfiguration()
    {
        HttpSession session=this.getThreadLocalRequest().getSession();
        ConfigStarCluster config=(ConfigStarCluster)session.getAttribute("configLoad");
        System.out.println("Salida de load Configuration");
        return(config.toHashMap());
    }
    
}
